<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :status-icon="true"
        >
          <el-form-item
            v-if="user.level < 3"
            label="所属村"
            prop="villageWrap"
          >
            <el-cascader
              v-model="ruleForm.villageWrap"
              :options="villageCascader"
              :props="villageProp"
              placeholder="请选择项目建设所属村"
              clearable
              @change="change"
            />
          </el-form-item>

          <el-form-item
            label="所属组"
            prop="group"
          >
            <el-select
              v-model.number="ruleForm.group"
              placeholder="请选择所属组"
              clearable
            >
              <el-option
                v-for="item in groupAtt"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="项目编号"
            prop="number"
          >
            <el-input
              v-model="ruleForm.number"
              placeholder="请输入项目编号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="项目名称"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入项目名称"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="是否招投标"
            prop="bidding"
          >
            <el-select
              v-model="ruleForm.bidding"
              clearable
              placeholder="请选择是否招投标"
            >
              <el-option
                v-for="(item, index) in ['招投标', '无招投标']"
                :key="index"
                :label="item"
                :value="index == 0"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否立项"
            prop="projected"
          >
            <el-select
              v-model="ruleForm.projected"
              placeholder="请选择是否立项"
              clearable
            >
              <el-option
                v-for="(item, index) in ['立项', '无立项']"
                :key="index"
                :label="item"
                :value="index == 0"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否实施"
            prop="implement"
          >
            <el-select
              v-model="ruleForm.implement"
              placeholder="请选择是否实施"
              clearable
            >
              <el-option
                v-for="(item, index) in ['已实施', '无实施']"
                :key="index"
                :label="item"
                :value="index == 0"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="实施方"
            prop="implementer"
          >
            <el-input
              v-model="ruleForm.implementer"
              type="textarea"
              placeholder="请输入实施方"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="验收方"
            prop="acceptor"
          >
            <el-input
              v-model="ruleForm.acceptor"
              type="textarea"
              placeholder="请输入验收方"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="监理方"
            prop="supervisor"
          >
            <el-input
              v-model="ruleForm.supervisor"
              type="textarea"
              placeholder="请输入监理方"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="工程款支付情况"
            prop="deliverySituation"
          >
            <el-input
              v-model="ruleForm.deliverySituation"
              type="textarea"
              placeholder="请输入工程款支付情况"
              clearable
            />
          </el-form-item>

          <el-form-item
            label="备注"
            prop="remarks"
          >
            <el-input
              v-model="ruleForm.remarks"
              type="textarea"
              placeholder="请输入相关备注信息"
              clearable
            />
          </el-form-item>
          <relatedDocuments
            :related-documents="documents"
            @getRes="getResRelatedDocuments"
          />
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? "立即创建" : "保存编辑" }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
import relatedDocuments from "@/components/My-Components/relatedDocuments";
export default {
  name: "Form",
  components: {
    relatedDocuments,
  },
  props: {
    id: {},
  },
  data() {
    return {
      ruleForm: {
        villageWrap: [],
        village: [],
        group: "",
        number: "",
        name: "",
        bidding: true,
        implement: true,
        projected: true,
        implementer: "",
        acceptor: "",
        supervisor: "",
        deliverySituation: "",
        remarks: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        villageWrap: [
          { required: true, message: "请选择项目建设所属村", trigger: "change" },
        ],
        number: [
          { required: false, message: "请输入项目编号", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        bidding: [
          {
            required: true,
            message: "请选择是否招投标",
            trigger: "change",
          },
        ],
        projected: [
          { required: true, message: "请选择是否立项", trigger: "change" },
        ],
        implement: [
          { required: true, message: "请选择是否实施", trigger: "change" },
        ],
        implementer: [
          { required: false, message: "请输入实施方", trigger: "blur" },
        ],
        acceptor: [
          { required: false, message: "请输入验收方", trigger: "blur" },
        ],
        supervisor: [{ required: false, message: "请输入监理方", trigger: "blur" }],
        deliverySituation: [{ required: false, message: "请输入工程款支付情况", trigger: "blur" }],
        remarks: [{ required: false, message: "请输入相关备注信息", trigger: "blur" }],
      },
      options: [],
      dialogImageUrl: "",
      dialogVisible: false,
      createForm: {},
      groupAtt: [],
      villageCascader: [],
      typeAtt: [
        {
          label: "现金收支",
          value: 0
        },
        {
          label: "银行收支",
          value: 1
        }
      ],
      villageProp: {
        value: "id",
        label: "name",
      },
      relatedDocuments: [],
      documents: [],
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  async created() {
    this.init();
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    getResRelatedDocuments(val) {
      this.relatedDocuments = val
      console.log(this.relatedDocuments)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resPip() {  
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
      this.createForm.relatedDocuments = this.relatedDocuments
      this.clearNullField(this.createForm, 'group')
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/project-construction`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: 'ProjectConstruction' });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(`/project-construction/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: 'ProjectConstruction' });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`project-construction/${id}?join=village&join=group`);

      // 处理图片 文件
      this.relatedDocuments = res.data.relatedDocuments
      this.documents = res.data.relatedDocuments

      const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

      const area = await this.$http.get(`town/${town.data.town.id}?join=area`);
      res.data.villageWrap = [
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ];
      //手动触发 查找 资源类型
      this.change([
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ])
      
      this.ruleForm = Object.assign({}, res.data);
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      debugger
      this.ruleForm.village = val[val.length - 1];
      const res = await this.$http.get(`village/${this.ruleForm.village}?join=group`);
      this.groupAtt = res.data.group
    },

    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
          //村级
        this.ruleForm.village = this.user.village.id
        this.change([this.ruleForm.village])
      } 
    },
  },
};
</script>
